const config = require('./config')
const util = require('./util')
const user = require('./user')

// true 不需要登录的path，false反之
function handelExcept(path) {
  // 不需要登录验证的path
  const except = [
    '/api/login',
    '/api/register'
  ]

  return except.indexOf(path) !== -1
}

// 处理返回的结果
function handleResponseData(res) {
  if (res.statusCode == 503) {
    // 未登录
    user.logout()
    return {
      code: 500,
      msg: ''
    }
  }

  if (res.statusCode == 200) {
    // 401未登录状态
    if (res.data.code == 422) {
      user.logout()
    }
    console.log('返回参数：')
    console.log(res.data)
    return res.data
  } else {
    
    return {
      code: 500,
      msg: '服务器维护中，请稍后重试！'
    }
  }
}
const httpClient = {
  request: function (method, path, data) {
    if (!handelExcept(path) && !user.hasLogin()) {
      // 未登录的处理
      user.logout()
      return new Promise((resolve, reject) => {
        resolve({})
      })
    }

    if (data == undefined) {
      data = {}
    }

    console.log('请求参数：'+path)
    console.log(data)
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    return new Promise((resolve, reject) => {
      wx.request({
        url: config.base_url + path,
        data: data,
        method: method,
        header: {
          Authorization: 'Bearer '+user.getData('access_token')
        },
        success: function (res) {
          wx.hideLoading()
          resolve(handleResponseData(res))
        },
        fail: function (err) {
          wx.hideLoading()
          resolve(handleResponseData(err))
        },
        complete: function (res) {
          wx.hideLoading()
          // console.log("request completed!");
        }
      })
    });
  },
  get: function (url, data) {
    return this.request('GET', url, data);
  },
  post: function (url, data) {
    return this.request('POST', url, data);
  }
};

module.exports = httpClient;
 
 